package com.controllers;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import com.daos.EmployeeDao;
import com.model.Employee;
import com.model.Role;

@Named
@Transactional
public class LoginController implements UserDetailsService {

	private EmployeeDao employeeDao;

	@Inject
	public LoginController(EmployeeDao userDao) {
		this.employeeDao = userDao;
	}

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {

		UserDetails user = null;
		try {
			Employee dbUser = employeeDao.getEmployeeByUsername(username);
			user = new User(dbUser.getUsername(), dbUser.getPassword(), true,
					true, true, true, getAuthorities(dbUser.getGroup()
							.getRoles()));
		} catch (Exception e) {
			
		}
		return user;
	}

	public Collection<GrantedAuthority> getAuthorities(Collection<Role> roles) {
		List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
		for (Role role : roles) {
			authList.add(new GrantedAuthorityImpl(role.getName()));
		}
		return authList;
	}

	public EmployeeDao getEmployeeDao() {
		return employeeDao;
	}

	public void setEmployeeDao(EmployeeDao employeeDao) {
		this.employeeDao = employeeDao;
	}

}
